using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Common.Unity.Extensions.PropertyMapper.Policies;
using Microsoft.Practices.ObjectBuilder2;

namespace Common.Unity.Extensions.PropertyMapper
{
	public class PropertyMappingStrategy<PolicyType> : PropertyMappingStrategyBase where PolicyType : IPropertyMappingPolicy
	{
		protected override IEnumerable<IPropertyMappingPolicy> ResolvePolicies( IBuilderContext context,
		                                                                        PropertyMappingKey key )
		{
			bool include = ShouldProcessBaseTypes( context );
			foreach ( PropertyMappingKey mappingKey in include ? PropertyMappingKeyHelper.ResolveHierarchy( key ) : new PropertyMappingKey[]{ key } )
			{
				IPropertyMappingPolicy policy = context.Policies.Get<PolicyType>( mappingKey );
				if ( policy != null )
				{
					yield return policy;
				}
			}
		}

		static bool ShouldProcessBaseTypes( IBuilderContext context )
		{
			IPropertyMapperProcessBaseTypesPolicy policy = context.Policies.Get<IPropertyMapperProcessBaseTypesPolicy>( context.BuildKey );
			return policy != null && policy.Enabled;
		}
	}
}